﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using IPR_StudyMeetingMrgSys.ViewModel;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.BLL;
using IPR_StudyMeetingMrgSys.Model;
using Newtonsoft.Json;
using log4net;
using System.Reflection;
using System.Data;
using Aspose;
using Aspose.Words;
using System.Security.Cryptography;
using System.Web;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http.Headers;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    /// <summary>
    /// 培训资料文件，包含其它的文档、视频、图片等文件
    /// </summary>
    public class TrainFilesController : ApiController
    {

        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        // POST: api/TrainFiles
        /// <summary>
        /// 培训文件管理增加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainFiles/Add")]
        public IHttpActionResult Add(Model.TrainFiles model)
        {

            log.Info(JsonConvert.SerializeObject(model));

            ResultMsg resultMsg = new ResultMsg(); 

            try
            {
                BLL.TrainFiles bllTrainFiles = new BLL.TrainFiles();
                if (!bllTrainFiles.Exists(model.TFName))
                {
                    if (new IPR_StudyMeetingMrgSys.BLL.TrainFiles().Add(model) > 0)
                    {
                        //返回token信息
                        resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                        resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                        resultMsg.Data = "培训文件信息增加成功！";
                    }
                    else
                    {
                        //返回token信息
                        resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                        resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                        resultMsg.Data = "培训文件信息增加失败！";
                    }
                }
                else
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                    resultMsg.Data = "培训文件信息已经存在，请不要重复！";
                }
            }
            catch (Exception exc)
            {

                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "培训文件信息增加异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        // POST: api/TrainFiles
        /// <summary>
        /// 培训文件信息分页查找
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainFiles/Search")]
        public IHttpActionResult Search(string swhere, int page, int limit)
        {
            log.Info(JsonConvert.SerializeObject(swhere));
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;

                if (!string.IsNullOrEmpty(swhere == null ? string.Empty : swhere.Trim()))
                {
                    Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                    swhere = string.Empty;
                    swhere = " 1=1 ";
                        //and (T.DepID="+LoginUser.DepID.ToString() +" or T.DepID="+LoginUser.DepPID.ToString()+") "; 与课程选择资料的地方冲突，暂进取消
                    foreach (var item in jsonObject)
                    {
                        if (item.Key == "TFName")
                        {
                            if(item.Value!="")
                                swhere += $" and TFName like '%{item.Value}%'";
                        }
                        if (item.Key == "TFAddUserName")
                        {
                            if(item.Value!="")
                                swhere += $" and TFAddUserName like '%{item.Value}%'";
                        }
                        if (item.Key == "start")
                        {
                            if(item.Value!="")
                                swhere += $"  and TFAddDateTime >='{item.Value}'";
                        }
                        if(item.Key=="end")
                        {
                            if(item.Value!="")
                                swhere += $" and TFAddDateTime <='{item.Value}'";
                        }
                        if (item.Key == "TFUploadDeptID")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" and TFUploadDeptID = {item.Value}";
                        }
                        if (item.Key == "TFIsUse")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" and TFIsUse = {item.Value}";
                        }
                        if (item.Key == "TFIsPass")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" and TFIsPass = {item.Value}";
                        }
                        if (item.Key == "FTID")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" and T.FTID = {item.Value}";
                        }
                        if (item.Key == "KKID")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" and T.KKID = {item.Value}";
                        }
                    }
                }
                int rowCount = 0;
                bool blExist = false;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainFiles().GetListByPage(swhere, "TFID", startindex, endindex,out rowCount);
                if (dsSearch != null)
                    if (dsSearch.Tables.Count > 0)
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                            resultMsg.Count = rowCount;
                            blExist = true;
                        }
                if (!blExist)
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.NoData;
                    resultMsg.Info = StatusCodeEnum.NoData.GetEnumText();
                    resultMsg.Data = "查询结果不存在！";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "查询异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 培训文件信息编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainFiles/Edit")]
        public IHttpActionResult Edit(Model.TrainFiles model)
        {
            log.Info(JsonConvert.SerializeObject(model));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.TrainFiles().Update(model))
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = "培训文件信息编辑成功！";
                }
                else
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                    resultMsg.Data = "培训文件信息编辑失败！";
                }
            }
            catch (Exception exc)
            {

                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = "培训文件信息编辑时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 培训文件信息删除(根据文件工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainFiles/Del")]
        public IHttpActionResult Del(Model.TrainFiles model)
        {
            log.Info(JsonConvert.SerializeObject(model));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.TrainFiles().Delete(model.TFID))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = "培训文件信息删除成功！";
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                    resultMsg.Data = "培训文件信息删除失败！";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = "培训文件信息删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }


        /// <summary>
        /// 文件信息删除(根据文件工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainFiles/DelList")]
        public IHttpActionResult DelList(string delidlist)
        {
            log.Info(JsonConvert.SerializeObject(delidlist));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.TrainFiles().DeleteList(delidlist))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = "文件信息删除成功！";
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                    resultMsg.Data = "文件信息删除失败！";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = "文件信息删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 文件审核
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainFiles/Audit")]
        public IHttpActionResult Audit(int tfid)
        {
            log.Info(JsonConvert.SerializeObject(tfid));

            ResultMsg resultMsg = new ResultMsg();
            try
            { 
                if (new IPR_StudyMeetingMrgSys.BLL.TrainFiles().FileAudit(tfid))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = "培训文件审核成功！";
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                    resultMsg.Data = "培训文件审核失败！";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = "培训文件信息删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        [HttpPost]
        [Route("api/TrainFiles/FileUpload")]
        public IHttpActionResult FileUpload()
        {
            log.Info("开始文件上传，文件数：" + HttpContext.Current.Request.Files.Count.ToString() );
            Res res = new Res();
            var FTID = HttpContext.Current.Request["FTID"].ToString();
            var KKID = HttpContext.Current.Request["KKID"].ToString();
            var TFUploadDeptID = HttpContext.Current.Request["TFUploadDeptID"].ToString();
            var TFFileLevel = HttpContext.Current.Request["TFFileLevel"].ToString();
            var TFFileKey = HttpContext.Current.Request["TFFileKey"].ToString();
            var TFReadTime = HttpContext.Current.Request["TFReadTime"].ToString() == "" ? "0" : HttpContext.Current.Request["TFReadTime"].ToString();
            var DepID= HttpContext.Current.Request["TFUploadDeptID"].ToString();
            string TFEndDateTime = HttpContext.Current.Request["TFEndDateTime"].ToString();
            var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;

            log.Info("开始文件上传:341" );
            var path = "";
            var fileName = "";
            if (file != null && file.ContentLength > 0)
            {
                fileName = Path.GetFileName(file.FileName);
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/uploads")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/uploads"));
                }
                path = Path.Combine(
                    HttpContext.Current.Server.MapPath("~/uploads"),
                    fileName
                );

                log.Info("开始文件上传:"+fileName);
                //file.SaveAs(path);
                #region 开始保存
                string sExt = System.IO.Path.GetExtension(fileName);
                string svrFilePathPlusName = "";
                //string sFactPathPDF = "";
                //if (sExt.ToUpper() == ".PDF")
                //{
                    //如果是PDF文件直接存储
                    file.SaveAs(path);
                    svrFilePathPlusName = "/uploads/" + fileName;
                //}
                //else if (sExt.ToUpper() == ".DOC" || sExt.ToUpper() == ".DOCX")
                //{
                //    log.Info("开始上传:" + sExt);
                //    //如果是word文件需要转换为pdf文件后，同时名称改变
                //    if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/uploaddocs")))
                //    {
                //        Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/uploaddocs"));
                //    }
                //    string strDt = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                //    string path1 = Path.Combine(
                //    HttpContext.Current.Server.MapPath("~/uploaddocs"),
                //    strDt + fileName
                //    );

                //    file.SaveAs(path1);

                //    Document doc = new Document(path1);
                //    path = Path.Combine(
                //        HttpContext.Current.Server.MapPath("~/uploads"),
                //        strDt + ".pdf"
                //    );
                //    sFactPathPDF = path;
                //    doc.Save(sFactPathPDF, Aspose.Words.SaveFormat.Pdf);
                //    svrFilePathPlusName = "/uploads/" + strDt + ".PDF";

                //    log.Info("保存上传:" + svrFilePathPlusName);
                //}
                //else
                //{
                //    //图片或者视频等其它文件直接存储
                //    file.SaveAs(path);
                //    svrFilePathPlusName = "/uploads/" + fileName;
                //}
                #endregion
                #region 汇总数据字段
                try
                {
                    Model.TrainFiles mTF = new Model.TrainFiles();
                    //mTF.TFID = new BLL.SysManage().GetMaxId("TrainFiles", "TFID");
                    mTF.TFName = fileName.Split('.')[0];
                    mTF.KKID = Convert.ToInt32(KKID);
                    mTF.FTID = Convert.ToInt32(FTID);
                    mTF.TFUploadDeptID = Convert.ToInt32(TFUploadDeptID);
                    mTF.TFFileLevel = TFFileLevel;
                    mTF.TFFileKey = TFFileKey;
                    mTF.TFReadTime = Convert.ToInt32(TFReadTime);
                    mTF.TFPath = path;
                    mTF.TFSize = file.ContentLength / 1024;
                    mTF.TFMD5 = MD5Encrypt(fileName, "ZZIPRYFB");
                    mTF.TFUseCount = 0;
                    mTF.TFIsPhoto = ".jpg|.png|.jpeg|.bmp|.gif".Contains(sExt.ToLower()) ? 1 : 0;
                    mTF.TFIsPass = 0;
                    mTF.TFAddUserID = (int)LoginUser.UserInfo.FID;
                    mTF.TFAddUserName = LoginUser.UserInfo.UserName;
                    mTF.TFAddDateTime = DateTime.Now;
                    mTF.TFServerPath = svrFilePathPlusName;
                    mTF.TFIsUse = 1;
                    mTF.TFDownCount = 0;
                    mTF.DepID = DepID;
                    if (TFEndDateTime != "")
                        mTF.TFEndDateTime = TFEndDateTime == "" ? Convert.ToDateTime("9999-12-31") : Convert.ToDateTime(TFEndDateTime);
                    log.Info("数据库存储时检查 重复！" );
                    bool blExist = new BLL.TrainFiles().Exists(mTF.TFName);
                    if (blExist)
                    {
                        //如果已经存在，说明上传重复，不处理
                        res.code = (int)StatusCodeEnum.NameExists;
                        res.msg = StatusCodeEnum.NameExists.GetEnumText();
                    }
                    else
                    {
                        log.Info("数据库开始存储！");

                        mTF.TFID = new BLL.SysManage().GetMaxId("TrainFiles", "TFID");
                        new BLL.TrainFiles().Add(mTF);
                        res.code = (int)StatusCodeEnum.FileUploadSucess;
                        res.msg = StatusCodeEnum.FileUploadSucess.GetEnumText();
                    }
                    res.data = new cdata();
                    res.data.src = "/uploads/" + file.FileName;
                }
                catch (Exception exc)
                {
                    log.Info("数据库开始存储错误"+exc.Message);
                    res.code = (int)StatusCodeEnum.FileUploadSucess;
                    res.msg = exc.Message;
                    res.data = new cdata();
                    res.data.src = "/uploads/" + file.FileName;
                }
                #endregion 
            }
            log.Info("文件数" + HttpContext.Current.Request.Files.Count.ToString() + "=" + fileName + "-" + path);
            return Json(res);
        }
        public string MD5Encrypt(string pToEncrypt, string sKey)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(pToEncrypt);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("X");
            }

            return byte2String;
        }


        [HttpGet]
        [Route("api/TrainFiles/FileDownload")]
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <returns></returns>      
        public async Task<HttpResponseMessage> FileDownload()
        {
            try
            {
                //string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Export\\list.txt");
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads\\20190810183357274.pdf");
                //string path1 = @"\uploads\20190810183357274.pdf";
                if (!string.IsNullOrWhiteSpace(path) && File.Exists(path))
                {

                    string filename = Path.GetFileName(path);
                    var stream = new FileStream(path, FileMode.Open);
                    HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StreamContent(stream)
                    };
                    resp.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = filename
                    };
                    resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    resp.Content.Headers.ContentLength = stream.Length;

                    return await Task.FromResult(resp);
                }
            }
            catch (Exception)
            {
            }
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }

        // GET: api/TrainFiles
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/TrainFiles/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/TrainFiles
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/TrainFiles/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/TrainFiles/5
        public void Delete(int id)
        {
        }
    }

    public class Res
    {
        /// <summary>
        /// 状态码
        /// </summary>
        public int code { get; set; }

        /// <summary>
        /// 操作信息
        /// </summary>
        public string msg { get; set; }

        private cdata mydata;
        /// <summary>
        /// 返回数据
        /// </summary>
        public cdata data
        {
            get { return mydata; }
            set { mydata = value; }
        }
    }
    public class cdata
    {
        /// <summary>
        /// 操作信息
        /// </summary>
        public string src { get; set; }
    }
}
